import router from './router'
import store from './store'
import {Message} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {getToken} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { resetRouter } from '@/router'

NProgress.configure({showSpinner: false}) // NProgress Configuration



const whiteList = ['/login', '/register/index', '/login/agent', '/login/store']; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
    // start progress bar
    NProgress.start()

    // set page title
    document.title = getPageTitle(to.meta.title)


    // determine whether the user has logged in

    const hasToken = getToken();
    if (hasToken) {
        if (to.path === '/login') {
            next({path: '/'});
            NProgress.done()
        } else if (to.path === '/login/agent') {
            next({path: '/'});
            NProgress.done()
        } else if (to.path === '/login/store') {
            next({path: '/'});
            NProgress.done()
        } else {
            const hasRoles = store.getters.roles && store.getters.roles.length > 0;

            if (hasRoles) {
                next()
            } else {
                try {
                    // const rules = await store.dispatch('user/getInfo');
                    // const accessRoutes = await store.dispatch('user/generateRoutes', rules);
                    // resetRouter();
                    // router.options.routes = router.options.routes.concat(accessRoutes);
                    // router.addRoutes(accessRoutes)
                    next()
                } catch (error) {
                    await store.dispatch('user/resetToken');
                    Message.error(error || 'Has Error');
                    next(`/login?redirect=${to.path}`);
                    NProgress.done()
                }
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next(`/login?redirect=${to.path}`)
            NProgress.done()
        }
    }
})

router.afterEach(() => {
    NProgress.done()
})
